package com.shf.service.impl;

import com.shf.domain.ResponseResult;
import com.shf.domain.entity.LoginUser;
import com.shf.domain.entity.User;
import com.shf.domain.vo.BlogUserLoginVo;
import com.shf.domain.vo.UserInfoVo;
import com.shf.service.BlogLoginService;
import com.shf.util.BeanCopyUtils;
import com.shf.util.JwtUtil;
import com.shf.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * @author 叶枫
 * @date 2023/10/29.
 */

@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        if(user.getUserName().length() < 2){
            throw new RuntimeException("用户名小于2");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        LoginUser loginUser =(LoginUser) authenticate.getPrincipal();

        String userId = loginUser.getUser().getId().toString();
        //把这个userid通过我们写的JwtUtil工具类转成密文，这个密文就是token值
        String jwt = JwtUtil.createJWT(userId);

        //将对象放入redis
        redisCache.setCacheObject("login"+userId,loginUser);
        //把User转化为UserInfoVo，再放入vo对象的第二个参数
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(jwt, userInfoVo);
        //响应结果
        return  ResponseResult.okResult(blogUserLoginVo);

    }

    @Override
    public ResponseResult logout() {
        //获取用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        LoginUser loginUser =(LoginUser) authentication.getPrincipal();

        //删除redis缓存中的用户

        Long userId = loginUser.getUser().getId();

        redisCache.deleteObject("login" + userId);

        //响应
        return ResponseResult.okResult();
    }
}
